import { View, Text } from '@tarojs/components';
import { Button, Dialog, Input, Picker } from '@nutui/nutui-react-taro';
import './index.less';
import { useEffect, useState } from 'react';
import { IVideo, IVoice } from '../..';
import { getUser } from '@/utils/user';
import Taro from '@tarojs/taro';
import request from '@/utils/request';

interface IProps {
  onTabbarChange: (index: number) => void;
  videoList: IVideo[];
  voiceList: IVoice[];
}

export default function Index(props: IProps) {
  const user = getUser();
  const [shareLink, setShareLink] = useState('');
  const [selectedVideoId, setSelectedVideoId] = useState('');
  const [selectedVoiceId, setSelectedVoiceId] = useState('');
  const [isVideoVisible, setIsVideoVisible] = useState(false);
  const [isVoiceVisible, setIsVoiceVisible] = useState(false);
  const [createDialogVisible, setCreateDialogVisible] = useState(false);
  const [confirmDialogVisible, setConfirmDialogVisible] = useState(false);

  useEffect(() => {
    console.log('props.videoList', props.videoList);
    console.log('props.voiceList', props.voiceList);
    if (props.videoList.length > 0) {
      setSelectedVideoId(props.videoList[0].id);
    }
    if (props.voiceList.length > 0) {
      setSelectedVoiceId(props.voiceList[0].id);
    }
  }, [props.videoList, props.voiceList]);

  const goCreate = () => {
    setConfirmDialogVisible(true);
  };

  const handleConfirmCreate = async () => {
    try {
      const selectedVideoObj = props.videoList.find(
        (item) => item.id === selectedVideoId
      );
      const selectedVoiceObj = props.voiceList.find(
        (item) => item.id === selectedVoiceId
      );

      if (!selectedVideoObj || !selectedVoiceObj || !shareLink) {
        Taro.showToast({
          title: '请完善创建信息',
          icon: 'none',
        });
        return;
      }

      setConfirmDialogVisible(false);
      setCreateDialogVisible(true);
      await request.post('/work/createWorkWithLinks', {
        userId: user.id,
        shareLink,
        videoLink: selectedVideoObj.url,
        voiceId: selectedVoiceObj.voiceId,
      });
    } catch (error) {
      console.error('创建失败:', error);
      Taro.showToast({
        title: '创建失败，请重试',
        icon: 'none',
      });
    }
  };

  return (
    <View className="dou-create">
      {!!user?.token && (
        <View>
          <View className="tips-wrap">
            <View className="tips-title">使用指南</View>
            <View>
              1、在底部「形象」和「声音」模块中
              <Text style={{ color: 'var(--nutui-color-primary)' }}>
                录入你的个人形象与声音信息
              </Text>
              。
            </View>
            <View>
              2、获取并粘贴你喜欢的
              <Text style={{ color: 'var(--nutui-color-primary)' }}>
                视频分享链接
              </Text>
              。
            </View>
            <View>3、选择你要使用的形象及声音。</View>
            <View>4、点击「创建」，即可快速复刻你的专属抖音作品。</View>
          </View>

          <View className="share-link">
            <View className="title">分享链接</View>
            <Input
              className="link-input"
              placeholder="请输入分享链接"
              value={shareLink}
              onChange={(val) => setShareLink(val)}
            />
          </View>

          <View className="share-video">
            <View className="title">选择形象</View>
            <View
              className="picker-trigger"
              onClick={() => setIsVideoVisible(true)}>
              {props.videoList.find((item) => item.id === selectedVideoId)
                ?.name || '请选择形象'}
            </View>
            <Picker
              visible={isVideoVisible}
              options={props.videoList.map((item) => ({
                text: item.name,
                value: item.id,
              }))}
              onConfirm={(list) => {
                setSelectedVideoId(list[0].value as string);
                setIsVideoVisible(false);
              }}
              onClose={() => setIsVideoVisible(false)}
            />
          </View>

          <View className="share-voice">
            <View className="title">选择声音</View>
            <View
              className="picker-trigger"
              onClick={() => setIsVoiceVisible(true)}>
              {props.voiceList.find((item) => item.id === selectedVoiceId)
                ?.name || '请选择声音'}
            </View>
            <Picker
              visible={isVoiceVisible}
              options={props.voiceList.map((item) => ({
                text: item.name,
                value: item.id,
              }))}
              onConfirm={(list) => {
                setSelectedVoiceId(list[0].value as string);
                setIsVoiceVisible(false);
              }}
              onClose={() => setIsVoiceVisible(false)}
            />
          </View>

          <View className="create-button">
            <Button block type="primary" onClick={goCreate}>
              <View className="button-content">
                <View className="text">创建</View>
                <View className="desc">{'(约100cc/次)'}</View>
              </View>
            </Button>
          </View>

          <View className="title">
            <View className="icon" />
            注意事项
          </View>
          <View className="content">
            1. 创作会消耗账户额度，请确保账户额度充足。
          </View>
          <View className="content">
            2.
            消耗额度根据视频长度(分享连接视频中的字数)而定，平均每分钟的视频消耗100cc
          </View>
          <View className="bottom"></View>
        </View>
      )}

      <Dialog
        title="确认创建"
        visible={confirmDialogVisible}
        onConfirm={handleConfirmCreate}
        onCancel={() => setConfirmDialogVisible(false)}>
        <View style={{ padding: '16px' }}>
          <View>确认创建该作品吗？</View>
        </View>
      </Dialog>

      <Dialog
        title="作品创作中"
        visible={createDialogVisible}
        footerDirection="vertical"
        hideCancelButton={true}
        confirmText="去查看"
        onConfirm={() => {
          setCreateDialogVisible(false);
          props.onTabbarChange(3);
        }}>
        <View style={{ height: 70, padding: 10 }}>
          <View style={{ textAlign: 'center', marginTop: 10 }}>
            大约需要5-10分钟时间
          </View>
          <View style={{ textAlign: 'center', marginTop: 10 }}>
            可以去作品列表查看作品状态
          </View>
        </View>
      </Dialog>
    </View>
  );
}
